package dht.run;

import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Random;
import java.util.Vector;

import dht.IClientAgent;
import dht.client.ClientAgentImpl;
import dht.entity.GlobalVariables;
import dht.entity.NodeInfo;
import dht.log.LogUtils;
import dht.storage.PathUtils;
import dht.tool.FileGenerator;
import dse.IOUtil;
import dse.modules.eln.EarthLikeNetwork;
import dse.modules.eln.NodeWithCoordinates;

public class Client {

	public void runClient(String configFile) throws Exception {
		GlobalVariables.initialize(configFile);

		LogUtils.initialize(0xffffffff, GlobalVariables.logFile);

		NodeInfo localInfo = new NodeInfo();
		localInfo.setIp(InetAddress.getLocalHost().getHostAddress());
		// localInfo.setPort(GlobalVariables.localPort);

		EarthLikeNetwork network = IOUtil
				.NetworkFromFile(GlobalVariables.networkFile);
		int nodeId = Math.abs(localInfo.hashCode()) % network.maxNodeId() + 1;
		localInfo.setX(((NodeWithCoordinates) network.lookupNode(nodeId))
				.getX());
		localInfo.setY(((NodeWithCoordinates) network.lookupNode(nodeId))
				.getY());

		NodeInfo masterInfo = new NodeInfo();
		masterInfo.setIp(InetAddress.getByName(GlobalVariables.masterIp)
				.getHostAddress());
		masterInfo.setPort(GlobalVariables.masterPort);

		nodeId = Math.abs(masterInfo.hashCode()) % network.maxNodeId() + 1;
		masterInfo.setX(((NodeWithCoordinates) network.lookupNode(nodeId))
				.getX());
		masterInfo.setY(((NodeWithCoordinates) network.lookupNode(nodeId))
				.getY());

		IClientAgent clientAgent = new ClientAgentImpl(localInfo, masterInfo);

		int fileNum = GlobalVariables.fakeFileNumber;
		HashMap<String, Integer> fileName2BlockNum = null;
		try {
			fileName2BlockNum = FileGenerator.generate(fileNum, 16);
		} catch (IOException e) {
			e.printStackTrace();
		}

		int readNum = 1000;
		int i = 0;
		Random ran = new Random(GlobalVariables.seed);

		Vector<String> fileNames = new Vector<String>();
		fileNames.addAll(fileName2BlockNum.keySet());
		while (i < readNum) {
			String fileName = fileNames.get(ran.nextInt(fileNames.size()));
			try {
				clientAgent.read(PathUtils.getMetaName(fileName));
			} catch (Exception e) {
				System.out.println("read failed: " + fileName);
			}
			i++;
		}
	}

	public static void main(String args[]) throws Exception {
		Client c = new Client();
		c.runClient(args[0]);
	}
}
